<template>
  <view class="content">
    <view class="top" :style="{ height: `${heightAuto}px` }">
      <view class="top_center">
        <view class="top1">
          <!-- <view class="top" :style="{ height: `${heightAuto}px` }">
      <view class="top1" :style="{ height: `${heightAuto - 160}px` }"> -->
          <view class="top1_bj">
            <image class="top1_dog_img" src="https://yidui.jiujiefang7979.cn/static/images/giftshare.png" mode="widthFix" style="width: 100%" lazy-load></image>
          </view>
          <view class="gift-amount-text">礼包卡:{{ amount }}包沐浴露</view>
        </view>
        <view class="xuxian">
          <view class="xuxian1"></view>
        </view>
        <view class="top2">
          <image class="image1" :src="avatarUrl || '/static/images/default.jpg'" mode="aspectFit"></image>
          <view class="text">
            <view>{{ nickName || maskPhoneNumberPartially(phone) }}</view>
            <view class="color_gray">送您礼包卡</view>
          </view>
          <image class="image2" :src="srcUrl" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    <view class="footer">
      <button class="footer-btn" open-type="share" size="mini">分享图片</button>
      <button class="footer-btn" @click="saveImage" size="mini">保存图片</button>
    </view>
    <!-- 隐藏canvas用于生成图片 -->
    <canvas canvas-id="shareCanvas" id="shareCanvas" :style="`width:${styleWidth};height:${styleHeight};position:absolute;left:-9999px;top:-9999px;`" :width="canvasWidth" :height="canvasHeight"></canvas>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getWxCode } from '@/api/gift';
import { useUserStoreHook } from '@/store/user';
// import { getCurrentInstance } from 'vue';
const heightAuto = ref(0);
const srcUrl = ref('');
const avatarUrl = ref('');
const nickName = ref('');
const phone = ref('');
const giftId = ref('');
const amount = ref(0);
const styleWidth = ref('750px');
const styleHeight = ref('1050px');
const canvasWidth = ref(750);
const canvasHeight = ref(1050);
const rpx2px = ref(1);

const getData = async () => {
  uni.showLoading({
    title: '获取信息中...',
    mask: true,
  });
  const res: any = await getWxCode({
    giftId: giftId.value,
  });
  uni.hideLoading();
  if (1 == res.result) {
    srcUrl.value = res.data.share_logo || '';
    avatarUrl.value = res.data.user?.avatar || uni.getStorageSync('user_avatarUrl');
    nickName.value = res.data.user?.nickname || uni.getStorageSync('user_nickName');
    phone.value = res.data.user?.mobile || uni.getStorageSync('phone');
    amount.value = res.data.amount || 0;
  }
};
const maskPhoneNumberPartially = (phoneNumber: string) => {
  // 检查输入是否为11位手机号
  if (!/^\d{11}$/.test(phoneNumber)) {
    return '-';
  }

  // 使用字符串的slice方法提取前3位、替换中间4位为'*'，并连接后4位
  return phoneNumber.slice(0, 3) + '****' + phoneNumber.slice(7);
};
// 在页面的onLoad方法中调用
onLoad(async (options: Record<string, any>) => {
  giftId.value = options?.giftId || '';
  await useUserStoreHook().getSign();
  getData();

  uni.getSystemInfo({
    success: function (res: any) {
      // 获取状态栏高度
      const statusBarHeight = res.statusBarHeight;
      // 获取窗口高度
      const windowHeight = res.windowHeight;
      // 计算可视区域高度（这里假设没有自定义导航栏或已经减去）
      const visibleHeight = windowHeight - statusBarHeight;
      // 将可视区域高度保存到页面的data中或进行其他处理
      heightAuto.value = visibleHeight - 80;
      console.log('heightAuto.value', visibleHeight, statusBarHeight, heightAuto.value);
    },
  });
});

onMounted(() => {
  const systemInfo = uni.getSystemInfoSync();
  const screenWidth = systemInfo.screenWidth;
  rpx2px.value = screenWidth / 750;
  styleWidth.value = 750 * rpx2px.value + 'px';
  styleHeight.value = 1050 * rpx2px.value + 'px';
  canvasWidth.value = 750 * rpx2px.value;
  canvasHeight.value = 1050 * rpx2px.value;
});

// 保存页面内容为图片（canvas绘制top_center区域视觉内容）
const saveImage = async () => {
  const ctx = uni.createCanvasContext('shareCanvas');
  const scale = rpx2px.value;
  const width = 750 * scale;
  const height = 1050 * scale;

  // 下载主图、头像、二维码
  const download = (url) =>
    new Promise((resolve) => {
      if (!url) return resolve('');
      if (url.startsWith('/static/')) return resolve(url);
      
      console.log('开始下载图片:', url);
      
      // 对于微信头像，尝试特殊处理
      if (url.includes('thirdwx.qlogo.cn')) {
        console.log('检测到微信头像URL，尝试特殊处理');
        // 先尝试直接下载
        uni.downloadFile({
          url,
          success: (res) => {
            console.log('微信头像下载成功:', url, res);
            if (res.statusCode === 200) resolve(res.tempFilePath);
            else {
              console.log('微信头像下载失败，状态码:', res.statusCode);
              resolve('');
            }
          },
          fail: (err) => {
            console.log('微信头像下载失败:', url, err);
            // 如果下载失败，返回空字符串，后续会使用默认头像
            resolve('');
          },
        });
      } else {
        // 普通图片下载
        uni.downloadFile({
          url,
          success: (res) => {
            console.log('下载成功:', url, res);
            if (res.statusCode === 200) resolve(res.tempFilePath);
            else {
              console.log('下载失败，状态码:', res.statusCode);
              resolve('');
            }
          },
          fail: (err) => {
            console.log('下载失败:', url, err);
            resolve('');
          },
        });
      }
    });

  const mainImgPath = await download('https://yidui.jiujiefang7979.cn/static/images/giftshare.png');
  const avatarPath = await download(avatarUrl.value || '/static/images/default.jpg');
  const qrPath = await download(srcUrl.value);
  
  console.log('图片下载结果:', {
    mainImgPath,
    avatarPath,
    qrPath,
    avatarUrl: avatarUrl.value
  });

  // 1. 上方圆角卡片（主图+礼包卡说明）
  const card1X = 40 * scale;
  const card1Y = 0;
  const card1W = width - 80 * scale;
  const card1H = 720 * scale; // 主图600+说明文字等，保持原有参数
  const cardRadius = 40 * scale;
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(card1X + cardRadius, card1Y);
  ctx.lineTo(card1X + card1W - cardRadius, card1Y);
  ctx.quadraticCurveTo(card1X + card1W, card1Y, card1X + card1W, card1Y + cardRadius);
  ctx.lineTo(card1X + card1W, card1Y + card1H - cardRadius);
  ctx.quadraticCurveTo(card1X + card1W, card1Y + card1H, card1X + card1W - cardRadius, card1Y + card1H);
  ctx.lineTo(card1X + cardRadius, card1Y + card1H);
  ctx.quadraticCurveTo(card1X, card1Y + card1H, card1X, card1Y + card1H - cardRadius);
  ctx.lineTo(card1X, card1Y + cardRadius);
  ctx.quadraticCurveTo(card1X, card1Y, card1X + cardRadius, card1Y);
  ctx.closePath();
  ctx.setFillStyle('#fff');
  ctx.fill();
  ctx.clip();
  // 上方卡片内容垂直居中分布，主图、说明、上下边距平均分配
  const card1ContentH = card1H;
  const imgSize = 600 * scale;
  const textH = 38 * scale; // 说明文字高度
  const gap = (card1ContentH - imgSize - textH) / 3;
  const imgX = (width - imgSize) / 2;
  const offset = 20 * scale; // 下移20px，可根据需要调整
  const imgY = card1Y + gap + offset;
  if (mainImgPath) ctx.drawImage(mainImgPath, imgX, imgY, imgSize, imgSize);
  ctx.setFontSize(38 * scale);
  ctx.setFillStyle('#ff9501');
  ctx.setTextAlign('center');
  ctx.fillText(`礼包卡:${amount.value}包沐浴露`, width / 2, imgY + imgSize + gap + textH / 2);
  ctx.restore();

  // 2. 橙色虚线（连接上下卡片）
  const dashY = card1Y + card1H; // 紧贴上方卡片底部
  ctx.setStrokeStyle('#ffb980');
  ctx.setLineWidth(8 * scale); // 虚线更粗
  ctx.setLineDash([10 * scale, 8 * scale], 0);
  ctx.beginPath();
  ctx.moveTo(card1X + cardRadius, dashY); // 左端到圆角结束处
  ctx.lineTo(card1X + card1W - cardRadius, dashY); // 右端到圆角结束处
  ctx.stroke();
  ctx.setLineDash([], 0);
  ctx.setLineWidth(1);

  // 3. 下方圆角卡片（顶部直角，底部圆角）
  const card2Y = dashY; // 紧贴虚线
  const card2H = 220 * scale;
  ctx.save();
  ctx.beginPath();
  // 左上圆角
  ctx.moveTo(card1X + cardRadius, card2Y);
  ctx.quadraticCurveTo(card1X, card2Y, card1X, card2Y + cardRadius);
  // 左边直线
  ctx.lineTo(card1X, card2Y + card2H - cardRadius);
  // 左下圆角
  ctx.quadraticCurveTo(card1X, card2Y + card2H, card1X + cardRadius, card2Y + card2H);
  // 底部直线
  ctx.lineTo(card1X + card1W - cardRadius, card2Y + card2H);
  // 右下圆角
  ctx.quadraticCurveTo(card1X + card1W, card2Y + card2H, card1X + card1W, card2Y + card2H - cardRadius);
  // 右边直线
  ctx.lineTo(card1X + card1W, card2Y + cardRadius);
  // 右上圆角
  ctx.quadraticCurveTo(card1X + card1W, card2Y, card1X + card1W - cardRadius, card2Y);
  // 顶部直线回到起点
  ctx.lineTo(card1X + cardRadius, card2Y);
  ctx.closePath();
  ctx.setFillStyle('#fff');
  ctx.fill();
  ctx.clip();
  // 头像、昵称、二维码横向平均分布
  const cardContentW = card1W;
  const sectionW = cardContentW / 3;
  // 头像
  ctx.save();
  ctx.beginPath();
  ctx.arc(card1X + sectionW / 2, card2Y + card2H / 2, 60 * scale, 0, 2 * Math.PI);
  ctx.clip();
  if (avatarPath) {
    console.log('绘制头像:', avatarPath);
    ctx.drawImage(avatarPath, card1X + sectionW / 2 - 60 * scale, card2Y + card2H / 2 - 60 * scale, 120 * scale, 120 * scale);
  } else {
    console.log('头像路径为空，绘制默认头像');
    // 绘制默认头像（渐变圆形）
    const gradient = ctx.createCircularGradient(
      card1X + sectionW / 2, 
      card2Y + card2H / 2, 
      0, 
      card1X + sectionW / 2, 
      card2Y + card2H / 2, 
      60 * scale
    );
    gradient.addColorStop(0, '#ff9501');
    gradient.addColorStop(1, '#ff6b35');
    ctx.setFillStyle(gradient);
    ctx.fill();
    
    // 绘制默认头像文字
    ctx.setFontSize(24 * scale);
    ctx.setFillStyle('#ffffff');
    ctx.setTextAlign('center');
    const defaultText = nickName.value ? nickName.value.charAt(0) : '用';
    ctx.fillText(defaultText, card1X + sectionW / 2, card2Y + card2H / 2 + 8 * scale);
  }
  ctx.restore();
  // 昵称
  ctx.setFontSize(32 * scale);
  ctx.setFillStyle('#333');
  ctx.setTextAlign('center');
  ctx.fillText(nickName.value, card1X + sectionW * 1.5, card2Y + card2H / 2 - 10 * scale);
  // 说明
  ctx.setFontSize(28 * scale);
  ctx.setFillStyle('#888');
  ctx.fillText('送您礼包卡', card1X + sectionW * 1.5, card2Y + card2H / 2 + 40 * scale);
  // 二维码
  if (qrPath) ctx.drawImage(qrPath, card1X + sectionW * 2 + (sectionW - 140 * scale) / 2, card2Y + card2H / 2 - 70 * scale, 140 * scale, 140 * scale);
  ctx.restore();

  // 4. 完成绘制
  ctx.draw(false, () => {
    uni.canvasToTempFilePath({
      canvasId: 'shareCanvas',
      success: (res) => {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            uni.showToast({ title: '保存成功', icon: 'success' });
          },
          fail: () => {
            uni.showToast({ title: '保存失败', icon: 'none' });
          },
        });
      },
      fail: () => {
        uni.showToast({ title: '生成图片失败', icon: 'none' });
      },
    });
  });
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: calc(100vh - 44px);
  background-color: white;
  .top {
    padding: 20px;
    background: linear-gradient(to bottom right, #feab85, transparent), /* 右上角到左下角 */ linear-gradient(to bottom left, #feea7e, transparent), /* 左上角到右下角 */ linear-gradient(to top right, #fa9aa6, transparent), /* 右下角到左上角 */ linear-gradient(to top left, #fc7e6a, transparent); /* 左下角到右上角 */

    display: flex;
    align-items: center;
    .top_center {
      width: 100%;
      .top1 {
        background-color: white;
        border-radius: 20px;
        padding: 40px 20px 24px;
        display: flex;
        flex-direction: column;
        align-items: center;
        .top1_bj {
          width: 100%;
          min-height: 220px;
          display: flex;
          align-items: center;
          justify-content: center;

          // background: linear-gradient(to bottom, #e0fbf8, transparent, #95d131 90%);
        }
        .top1_dog_img {
          width: 100%;
          height: auto;
          display: block;
        }
        .gift-amount-text {
          margin-top: 12px;
          text-align: center;
          font-size: 18px;
          color: #ff9501;
          font-weight: bold;
          letter-spacing: 2px;
        }
      }

      .xuxian {
        margin-left: 20px;
        margin-right: 20px;
        background-color: white;
        .xuxian1 {
          border-bottom: 2px dashed #fb7b68;
        }
      }

      .top2 {
        height: 160px;
        background-color: white;
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center; //居中
        padding: 20px;
        .image1 {
          width: 180rpx;
          height: 180rpx;
          border-radius: 50%;
        }
        .image2 {
          width: 180rpx;
          height: 180rpx;
        }
        .text {
          padding-left: 10px;
          padding-right: 10px;

          .color_gray {
            margin-top: 4px;
          }
        }
      }
    }
  }

  .footer {
    width: 100%;
    height: 80px;
    position: fixed;
    bottom: 0;
    background-color: white;
    padding: 10px 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .footer-btn {
      flex: 1;
      background-color: #ff9501;
      color: white;
      border-radius: 30px;
      height: 50px;
      line-height: 50px;
      font-size: 1.2rem;
      margin: 0 8px;
    }
  }
}
</style>

<script lang="ts">
export default {
  onShareAppMessage() {
    const userId = uni.getStorageSync('user_id');
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const giftId = currentPage.options?.giftId || '';
    return {
      title: '我送你一张礼包卡，快来领取吧！',
      path: `pages/dog/index?id=${userId}&giftId=${giftId}`,
      imageUrl: 'https://yidui.jiujiefang7979.cn/static/images/giftshare.png',
    };
  },
};
</script>
